import Mock from 'mockjs'
import { parseTime } from '@/utils'
let userData = [{
    id: 1,
    user_name: 'admin',
    password: '123456',
    nick_name: '超级管理员',
    email: 'xxxx666@163.com',
    user_pic: ''
}]
let articleInfoData = []

// 用户表
{
    let data = userData
    // 用户登录
    Mock.mock('/en_user/login', 'post', o => {
        let p = JSON.parse(o.body)
        let r = data.filter(c => c.user_name == p.user_name && c.password == p.password)
        if (r.length) {
            return {
                code: 0,
                msg: '登录成功',
                data: {
                    token: 'token-' + JSON.stringify(r[0])
                }
            }
        } else {
            return {
                code: 1,
                msg: '登录失败，用户名或密码不正确',
            }
        }
    })
    // 用户列表
    Mock.mock('/en_user/list', 'get', _ => {
        return {
            code: 0,
            data
        }
    })
    // 用户信息
    Mock.mock('/en_user/userInfo', 'get', req => {
        let body = JSON.parse(req.body)
        let userId = JSON.parse(body.token.replace('token-', '')).id
        let res = data.filter(c => c.id == userId)
        return {
            code: 0,
            data: res[0]
        }
    })
    // 修改用户信息
    Mock.mock('/en_user/update', 'post', req => {
        let body = JSON.parse(req.body)
        delete body.token
        let i = data.findIndex(c => c.id == body.id)
        data.splice(i, 1, body)
        return {
            code: 0,
            msg: '修改成功'
        }
    })
    // 修改密码
    Mock.mock('/en_user/modifyPwd', 'post', req => {
        let body = JSON.parse(req.body)
        let userId = JSON.parse(body.token.replace('token-', '')).id
        let curr = data.find(c => c.id == userId)
        if (body.oldPwd != curr.password) {
            return {
                code: 1,
                msg: '原密码不正确'
            }
        }
        if (body.password != body.twicePwd) {
            return {
                code: 1,
                msg: '二次密码不一致'
            }
        }
        curr.password = body.password
        return {
            code: 0,
            msg: '密码修改成功！'
        }

    })
    // 用户注册
    Mock.mock('/en_user/register', 'post', req => {
        let body = JSON.parse(req.body)
        if (data.filter(c => c.user_name == body.user_name).length) {
            return {
                code: 1,
                msg: '用户名已存在'
            }
        }
        data.push({
            id: Mock.mock('@id'),
            ...body
        })
        return {
            code: 0,
            msg: '注册成功，请返回登陆！'
        }
    })
}

// 菜单表
{
    let menus = [{
        "name": "article",
        "path": "/article",
        "hidden": false,
        "component": "Layout",
        "alwaysShow": true,
        "meta": {
            "title": "文章管理",
            "icon": "article",
            "noCache": false,
            "link": null
        },
        "children": [{
            "name": "articleCate",
            "path": "cate",
            "hidden": false,
            "component": "article/cate/index",
            "meta": {
                "title": "文章类别",
                "icon": "user",
                "noCache": false,
                "link": null
            }
        }, {
            "name": "articleInfo",
            "path": "info",
            "hidden": false,
            "component": "article/info/index",
            "meta": {
                "title": "文章信息",
                "icon": "peoples",
                "noCache": false,
                "link": null
            }
        }]
    }, {
        "name": "center",
        "path": "/center",
        "hidden": false,
        "component": "Layout",
        "alwaysShow": true,
        "meta": {
            "title": "个人中心",
            "icon": "article",
            "noCache": false,
            "link": null
        },
        "children": [{
            "name": "centerInfo",
            "path": "info",
            "hidden": false,
            "component": "center/index",
            "meta": {
                "title": "个人信息",
                "icon": "user",
                "noCache": false,
                "link": null
            }
        }, {
            "name": "modifyPwd",
            "path": "modifyPwd",
            "hidden": false,
            "component": "center/modifyPwd",
            "meta": {
                "title": "修改密码",
                "icon": "user",
                "noCache": false,
                "link": null
            }
        }]
    }]
    Mock.mock('/en_menus', _ => menus)
}

// 文章分类表
{
    let data = [{
        id: 1,
        name: '历史',
        alias: 'lishi'
    }, {
        id: 2,
        name: '文娱',
        alias: 'wenyu'
    }]
    // for (let i = 0; i < 10; i++) {
    //     data.push({
    //         id: Mock.mock("@id"),
    //         name: Mock.mock("@ctitle"),
    //         alias: Mock.mock("@title")
    //     })
    // }
    Mock.mock('/en_article_cate/cate', 'get', _ => {
        return {
            code: 0,
            data
        }
    })
    Mock.mock('/en_article_cate/cate', 'post', req => {
        let body = JSON.parse(req.body)
        delete body.token
        data.push({
            id: Mock.mock("@id"),
            ...body
        })
        return {
            code: 0,
            msg: '新增成功'
        }
    })
    Mock.mock('/en_article_cate/cate', 'put', req => {
        let body = JSON.parse(req.body)
        let editIndex
        for (let i = 0; i < data.length; i++) {
            if (data[i].id == body.id) {
                editIndex = i
                break
            }
        }
        data.splice(editIndex, 1, body)
        return {
            code: 0,
            msg: '编辑成功'
        }
    })
    Mock.mock(RegExp('/en_article_cate/cate/' + '.*'), 'delete', req => {
        let id = req.url.replace('/en_article_cate/cate/', '')
        let delIndex
        for (let i = 0; i < data.length; i++) {
            if (data[i].id == id) {
                delIndex = i
                break
            }
        }
        data.splice(delIndex, 1)
        return {
            code: 0,
            msg: '删除成功'
        }
    })
    // 文章分类-每类数量
    Mock.mock('/en_article_cate/cate_group', 'get', req => {
        let countHandler = cate => {
            cate.total = 0
            articleInfoData.forEach(infoItem => {
                if (infoItem.cate_id == cate.id) cate.total++
            })
        }
        data.forEach(c => countHandler(c))
        return {
            code: 0,
            data
        }
    })
}

// 文章详情表
{
    let data = articleInfoData
    for (let i = 0; i < 3; i++) {
        data.push({
            id: Mock.mock("@id"),
            title: Mock.mock('@ctitle'),
            content: Mock.mock('@cparagraph(1, 1)'),
            pub_date: Mock.mock('@date'),
            cate_id: Mock.mock('@integer(1, 2)'),
            author_id: userData[0].id
        })
    }
    // 文章总数
    Mock.mock('/en_article_info/info/count', 'get', _ => {
        return {
            code: 0,
            data: data.length
        }
    })
    // 文章数量（按天划分）
    Mock.mock(RegExp('/en_article_info/info_group_pub_date' + '.*'), req => {
        let res = {}
        data.forEach(c => {
            if (res[c.pub_date]) {
                res[c.pub_date]++
            } else {
                res[c.pub_date] = 1
            }
        })
        let urlArr = req.url.split('?')
        if (urlArr.length > 1) {
            let date = urlArr[1].split('=')[1]
            return {
                code: 0,
                data: res[date] || 0
            }
        }
        return {
            code: 0,
            data: res
        }
    })
    Mock.mock(RegExp('/en_article_info/info' + '.*'), 'get', req => {
        let urlArr = req.url.split('?')
        let query = {}
        urlArr[urlArr.length - 1].split('&').forEach(c => query[c.split('=')[0]] = c.split('=')[1])
        // 处理搜索条件
        const searchMap = ['cate_id', 'author_id']
        let searchRes = data.filter(c => {
            for (let i = 0; i < searchMap.length; i++) {
                let k = searchMap[i]
                if (query[k] != undefined && c[k] != query[k]) {
                    return false
                }
            }
            return true
        })
        // 处理分页条件
        let { pageNum = 1, pageSize = 10 } = query
        let start = (pageNum - 1) * pageSize // [ 闭区间
        let end = pageNum * pageSize // ) 开区间
        let pageRes = []
        // 溢出处理
        if (start > searchRes.length) {
            start = searchRes.length - pageSize
            end = searchRes.length
        }
        pageRes = searchRes.filter((c, i) => {
            if (i >= start && i < end) return true
        })
        return {
            code: 0,
            data: pageRes,
            total: searchRes.length
        }
    })
    Mock.mock('/en_article_info/info', 'post', req => {
        let body = JSON.parse(req.body)
        let userId = JSON.parse(body.token.replace('token-', '')).id
        delete body.token
        data.push({
            id: Mock.mock("@id"),
            pub_date: parseTime(new Date(), 'yyyy-MM-dd'),
            ...body,
            author_id: userId
        })
        return {
            code: 0,
            msg: '新增成功'
        }
    })
    Mock.mock('/en_article_info/info', 'put', req => {
        let body = JSON.parse(req.body)
        let editIndex
        for (let i = 0; i < data.length; i++) {
            if (data[i].id == body.id) {
                editIndex = i
                break
            }
        }
        delete body.token
        data.splice(editIndex, 1, body)
        return {
            code: 0,
            msg: '编辑成功'
        }
    })
    Mock.mock(RegExp('/en_article_info/info' + '.*'), 'delete', req => {
        let id = req.url.replace('/en_article_cate/cate/', '')
        let delIndex
        for (let i = 0; i < data.length; i++) {
            if (data[i].id == id) {
                delIndex = i
                break
            }
        }
        data.splice(delIndex, 1)
        return {
            code: 0,
            msg: '删除成功'
        }
    })
}


